
$(function () {
  // 缩放图展示
  function infoZoomProduct () {
    const $mainImg = $('.pd-products-img-container img')
    const $thumbnails = $('.pd-description-bar ol li')

    // 默认显示第一个
    const $first = $thumbnails.eq(0)
    $first.addClass('selected')
    $mainImg.attr('src', $first.find('img').attr('src'))
    // 点击切换
    $thumbnails.on('click', function () {
      $(this).addClass('selected').siblings().removeClass('selected')
      const newSrc = $(this).find('img').attr('src')
      $mainImg.attr('src', newSrc)
    })
  }

  const $img = $(".show-3d-img");
  const totalFrames = 124; // 帧数(图片数量)
  let currentFrame = 0;
  let interval = null;
  let isPlaying = false;
  let rotateDirection = 1; // 1 向右（顺时针），-1 向左（逆时针）

  // 图片路径函数
  const getFrameSrc = (index) => {
    const frameNum = String(index).padStart(0, '0'); // 01, 02, 03 ...
    return `../../img/PC/3DMaterial/download (${frameNum}).jpg`;
  };

  // 显示对应帧
  const showFrame = (index) => {
    if (index < 1) index = totalFrames;
    if (index > totalFrames) index = 1;
    currentFrame = index;
    $img.attr("src", getFrameSrc(currentFrame));
  };

  // 自动旋转
  const startAutoRotate = () => {
    if (isPlaying) return;
    isPlaying = true;
    $(".btn-toggle").html(`
          <img class="player-btn" src="../../img/svg/pause.svg" alt="pause">
      `);
    interval = setInterval(() => {
      showFrame(currentFrame + rotateDirection);
    }, 60);
  };

  // 停止旋转
  const stopAutoRotate = () => {
    isPlaying = false;
    clearInterval(interval);
    $(".btn-toggle").html(`
      <img class="player-btn" src="../../img/svg/play.svg" alt="play"></img>`);
  };

  // 初始化按钮
  function initPlayerButtons () {
    $(".btn-toggle").on("click", function () {
      if (isPlaying) stopAutoRotate();
      else startAutoRotate();
    });

    $(".btn-prev").on("click", () => {
      stopAutoRotate();
      rotateDirection = -1;
      showFrame(currentFrame - 1);
    });

    $(".btn-next").on("click", () => {
      stopAutoRotate();
      rotateDirection = 1;
      showFrame(currentFrame + 1);
    });
  }

  // 拖动控制
  let isDragging = false;
  let startX = 0;
  let lastDiff = 0;

  $img.attr("draggable", false);

  $img.on("mousedown", (e) => {
    e.preventDefault();
    stopAutoRotate();
    isDragging = true;
    startX = e.pageX;
  });

  $(document).on("mousemove", (e) => {
    if (!isDragging) return;
    const diff = e.pageX - startX;
    lastDiff = diff; // 记录最后一次移动方向

    if (Math.abs(diff) > 5) {
      const frameChange = diff > 0 ? 1 : -1;
      showFrame(currentFrame + frameChange);
      startX = e.pageX;
    }
  });

  $(document).on("mouseup mouseleave", () => {
    if (isDragging) {
      // 根据拖动方向决定后续自动旋转方向
      rotateDirection = lastDiff > 0 ? 1 : -1;
      startAutoRotate();
    }
    isDragging = false;
  });

  // 页面加载后自动旋转
  startAutoRotate();
  infoZoomProduct()
  initPlayerButtons()
})
